import {request} from "../../utils/util";

Page({
  data: {
    downTime: '4分59秒',
    sec: 300,
    timer: null,
    discount: false,
    showSelPay: false,
    orderData: {},
    form: {
      order_sn: '',
      pay_money: '',
      point: 0,
      remarks: '', // 备注
    },
    pointDeduction: 0, // 积分可抵扣金额
    deductPoint: 0, // 需要花费的积分
    payForm: {
      order_sn: '',
      pay_money: '',
    }
  },
  onInputChange(e) {
    const { value } = e.detail;
    const { name } = e.currentTarget.dataset;
    const { form } = this.data;
    this.setData({
      form: { ...form, [name]: value }
    });
  },
  discountChange (e) {
    if (this.data.orderData.user_point <= 0) {
      return false
    }
    this.setData({
      discount: !this.data.discount
    })
    this.calcShowMoney()
  },
  // 计算积分可抵扣的金额，以及需要花费的积分
  calcPointDeduction() {
    let { amount, pointToBalance, user_point } = this.data.orderData
    let pointDeduction = (pointToBalance * user_point).toFixed(2)
    let deductPoint = user_point
    if (pointDeduction*1 > amount*1) {
      pointDeduction = amount
      // 积分太多，抵扣金额大于支付金额时，需重新计算实际花费的积分，向上取整
      deductPoint = Math.ceil(amount / pointToBalance)
    }
    this.setData({
      pointDeduction,
      deductPoint
    })
  },
  calcShowMoney() {
    if (this.data.discount) {
      this.setData({
        form: {
          ...this.data.form,
          pay_money: (this.data.orderData.amount - this.data.pointDeduction).toFixed(2),
          point: this.data.deductPoint
        },
      })
    } else {
      this.setData({
        form: {
          ...this.data.form,
          pay_money: this.data.orderData.amount,
          point: 0
        },
      })
    }
  },
  toPay () {
    this.setData({
      form: {
        ...this.data.form,
        order_sn: this.data.orderData.order_sn
      },
    })
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/payment/order`,
      method: 'POST',
      data: this.data.form,
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          this.setData({
            payForm: {
              order_sn: this.data.form.order_sn,
              pay_money: this.data.form.pay_money,
            },
            showSelPay: true
          })
        } else if (code === 201) {
          wx.showToast({
            title: '支付成功！',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/sportsOrder/index'
            })
          }, 1000)
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  closePay() {
    this.setData({
      showSelPay: false
    })
  },
  getTime () {
    this.timer =  setInterval(() => {
      if (this.data.sec <= 0) {
        clearInterval(this.timer)
        this.orderOutDate()
        return false
      }
      this.data.sec -= 1;
      let m = Math.floor(this.data.sec/60), s = this.data.sec%60
      let downTime = (m < 10 ? ('0' + m) : m) + '分' + (s < 10 ? ('0' + s) : s) + '秒'
      this.setData({downTime})
    }, 1000)
  },
  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定取消当前订单吗？',
      success: (res) => {
        if (res.confirm) {
          request({
            url: `/api/web/venue/orders/${this.data.orderData.id}`,
            method: 'DELETE',
            success: ({ code, message }) => {
              if (code === 200) {
                wx.showToast({
                  title: '取消成功！',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 1000)
              } else {
                wx.showToast({
                  title: message,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  orderOutDate() {
    wx.showModal({
      title: '提示',
      content: '当前订单已过期！',
      confirmText: '知道了',
      showCancel: false,
      success (res) {
        if (res.confirm) {
          wx.navigateBack()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onShow () {
    this.options.data = decodeURIComponent(this.options.data)
    const data = JSON.parse(this.options.data)
    data.venue_order_subs.forEach(item => {
      item.order_date_show = item.order_date.substr(5)
      item.start_time_show = item.start_time.substr(0, 5)
      item.end_time_show = item.end_time.substr(0, 5)
    })
    data.created_at = data.created_at.replace(/\-/g, '/')
    const current = +new Date()
    const createTime = +new Date(data.created_at)
    const outDateSec = 300 // 过期分钟数
    const countDownSec = outDateSec - Math.ceil((current - createTime) / 1000)
    if (countDownSec < 1) {
      this.orderOutDate()
      return false
    }
    this.setData({
      orderData: data,
      sec: countDownSec
    })
    this.getTime();
    this.calcPointDeduction()
    this.calcShowMoney();
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },
  onHide() {
    clearInterval(this.timer)
  }
})
